package com.itheima.reggie.controller;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrdersDto;
import com.itheima.reggie.entity.OrderDetail;
import com.itheima.reggie.entity.Orders;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

//订单
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;
    @Autowired
    private OrderDetailService orderDetailService;

    //用户下单
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        orderService.submit(orders);
        return R.success("下单成功");
    }

    @GetMapping("userPage")
    public R queryPage(Integer page,Integer pageSize){
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        orderService.page(pageInfo);
        List<Orders> records = pageInfo.getRecords();
        long total = pageInfo.getTotal();
        List<OrdersDto> list = records.stream().map(orders ->{
            OrdersDto ordersDto = new OrdersDto();
            BeanUtil.copyProperties(orders,ordersDto);
            LambdaQueryWrapper<OrderDetail> lqw = new LambdaQueryWrapper<>();
            lqw.eq(OrderDetail::getOrderId,ordersDto.getNumber());
            List<OrderDetail> orderDetails = orderDetailService.list(lqw);
            ordersDto.setOrderDetails(orderDetails);
            return ordersDto;
        }).collect(Collectors.toList());
        Map map = new HashMap();
        map.put("total",total);
        map.put("records",list);
        return R.success(map);
    }
}
